package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author : [chenxys]
 * @version : [v1.0]
 * @Description : 后台权限控制
 * @createTime : [2022/5/31 17:18]
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
     /**
      * uerService
      * 使用dubbo通过网络远程调用服务提供方获取数据库中的用户信息
      */
     @Reference
     private UerService uerService;

    /**
     * 根据用户名查询数据库获取用户信息
     * @author chenxys
     * @param username 用户名
     * @return org.springframework.security.core.userdetails.UserDetails
     */
     @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = uerService.findByUsername(username);
        if (user == null){
            //用户名不存在
            return  null;
        }
        //权限集合
         List<GrantedAuthority> list = new ArrayList<>();
        //获取当前用户所拥有的角色
         Set<Role> roles = user.getRoles();
        //遍历获取
         for (Role role : roles) {
             //为当前用户授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取当前角色对应的权限集合
             Set<Permission> permissions = role.getPermissions();
             for (Permission permission : permissions) {
                 //遍历权限集合，对当前用户授予权限
                 list.add(new SimpleGrantedAuthority(permission.getKeyword()));
             }
         }
         //对当前用户的密码进行加密
         return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
